package com.rocching.easychat;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.rocching.easychat.core.CmdNotificationMessageProvider;
import com.rocching.easychat.core.ContactNotificationMessageProvider;
import com.rocching.easychat.core.ConversationDataProcessor;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.ProfileNotificationMessageProvider;
import com.rocching.easychat.core.SubConversationListActivity;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.db.LocalUserService;
import com.rocching.easychat.model.AppConst;
import com.rocching.easychat.model.FriendModel;
import com.rocching.easychat.model.GroupMemberModel;
import com.rocching.easychat.model.GroupModel;
import com.rocching.easychat.model.GroupUpdateModel;
import com.rocching.easychat.model.UserModel;
import com.rocching.easychat.service.FriendService;
import com.rocching.easychat.service.GroupService;
import com.rocching.easychat.util.AppUtil;
import com.rocching.easychat.util.JsonUtil;
import com.rocching.easychat.util.StringUtil;

import java.util.List;
import java.util.Objects;

import io.rong.imkit.IMCenter;
import io.rong.imkit.MessageInterceptor;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.UserDataProvider;
import io.rong.imkit.userinfo.model.GroupUserInfo;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.CommandNotificationMessage;
import io.rong.message.ContactNotificationMessage;
import io.rong.message.ProfileNotificationMessage;
import io.rong.push.RongPushClient;
import io.rong.push.pushconfig.PushConfig;

public class EasyChatApp extends Application {
    private final String TAG = EasyChatApp.class.getName();
    @SuppressLint("StaticFieldLeak")
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();

        init();
    }

    public static Context getContext() {
        return context;
    }

    private void init() {
        context = this;

//        initPushConfig();

        RongIM.init(this, AppConst.RC_APP_KEY, true);

        RouteUtils.registerActivity(RouteUtils.RongActivityType.ConversationListActivity, MainActivity.class);
        RouteUtils.registerActivity(RouteUtils.RongActivityType.SubConversationListActivity, SubConversationListActivity.class);

        RongConfigCenter.conversationListConfig().setDataProcessor(new ConversationDataProcessor());
        RongConfigCenter.conversationConfig().addMessageProvider(new ProfileNotificationMessageProvider());
        RongConfigCenter.conversationConfig().addMessageProvider(new ContactNotificationMessageProvider());
        RongConfigCenter.conversationConfig().addMessageProvider(new CmdNotificationMessageProvider());

        RongConfigCenter.gatheredConversationConfig().setGatherConversationPortrait(Conversation.ConversationType.SYSTEM, AppUtil.getSystemPhoto());
        RongConfigCenter.gatheredConversationConfig().setConversationTitle(Conversation.ConversationType.SYSTEM, R.string.msg_system_tip);

        initInfoProvider();
        initMessageListener();
//        initMessageInterceptor();
    }

    private void initPushConfig() {
        PushConfig pushConfig = new PushConfig.Builder().enableHWPush(true).build();
        RongPushClient.setPushConfig(pushConfig);
    }

    private void initInfoProvider() {
        try {
            RongUserInfoManager manager = RongUserInfoManager.getInstance();
            manager.setUserInfoProvider(new UserDataProvider.UserInfoProvider() {
                @Override
                public UserInfo getUserInfo(String userId) {
                    FriendService.getInstance().getFriend(userId, new IApiCallback<FriendModel>() {
                        @Override
                        public void onResponse(boolean succeeded, String body, FriendModel data) {
                            Log.i(TAG, "the data is:" + JsonUtil.toJson(data));
                            if (succeeded) {
                                manager.refreshUserInfoCache(AppUtil.getUserInfo(data));
                            }
                        }
                    });
                    return null;
                }
            }, true);

            manager.setGroupInfoProvider(new UserDataProvider.GroupInfoProvider() {
                @Override
                public Group getGroupInfo(String groupId) {
                    GroupService.getInstance().getGroupInfo(AppUtil.getGroupId(groupId), new IApiCallback<GroupModel>() {
                        @Override
                        public void onResponse(boolean succeeded, String body, GroupModel data) {
                            Log.i(TAG, "the data is:" + JsonUtil.toJson(data));
                            if (succeeded) {
                                if (Objects.isNull(data)) {
                                    return;
                                }
                                manager.refreshGroupInfoCache(new Group(groupId, data.getName(), AppUtil.getGroupPhotoUri(data.getPhoto())));
                                refreshGroupUserInfo(manager, groupId, data.getMemberList());
                            }
                        }
                    });
                    return null;
                }
            }, true);

            manager.setGroupUserInfoProvider(new UserDataProvider.GroupUserInfoProvider() {
                @Override
                public GroupUserInfo getGroupUserInfo(String groupId, String userId) {
                    GroupService.getInstance().getGroupInfo(AppUtil.getGroupId(groupId), new IApiCallback<GroupModel>() {
                        @Override
                        public void onResponse(boolean succeeded, String body, GroupModel data) {
                            Log.i(TAG, "the data is:" + JsonUtil.toJson(data));
                            if (succeeded) {
                                if (Objects.isNull(data)) {
                                    return;
                                }
                                refreshGroupUserInfo(manager, groupId, data.getMemberList());
                            }
                        }
                    });
                    return null;
                }
            }, true);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private void initMessageListener() {
        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int left, boolean hasPackage, boolean offline) {
                Log.i(TAG, "the left is:" + left);
                Log.i(TAG, "the has package is:" + hasPackage);
                Log.i(TAG, "the offline is:" + offline);

                MessageContent content = message.getContent();
                if (content instanceof ProfileNotificationMessage) {
                    String data = ((ProfileNotificationMessage) content).getData();
                    refreshUserInfo(data);
                } else if (content instanceof ContactNotificationMessage) {
                    String operation = ((ContactNotificationMessage) content).getOperation();
                    if (operation.equals(AppConst.OPERATION_RESPONSE)) {
                        String userId = ((ContactNotificationMessage) content).getSourceUserId();
                        RongUserInfoManager.getInstance().getUserInfo(userId);
                    }
                } else if (content instanceof CommandNotificationMessage) {
                    String name = ((CommandNotificationMessage) content).getName();
                    if (name.equals(AppConst.OPERATION_GROUP_UPDATE)) {
                        refreshGroupInfo(((CommandNotificationMessage) content).getData());
                    }
                }
                return true;
            }
        });
    }

    private void initMessageInterceptor() {
        IMCenter.getInstance().setMessageInterceptor(new MessageInterceptor() {
            @Override
            public boolean interceptReceivedMessage(Message message, int left, boolean hasPackage, boolean offline) {
                MessageContent content = message.getContent();
                if (content instanceof ProfileNotificationMessage) {
                    String data = ((ProfileNotificationMessage) content).getData();
                    refreshUserInfo(data);
                    return true;
                }
                return false;
            }

            @Override
            public boolean interceptOnSendMessage(Message message) {
                return false;
            }

            @Override
            public boolean interceptOnSentMessage(Message message) {
                return false;
            }
        });
    }

    private void refreshUserInfo(String data) {
        if (StringUtil.isNotEmpty(data)) {
            UserModel model = JsonUtil.parseObject(data, UserModel.class);
            if (model != null) {
                String userId = AppUtil.getTargetUserId(model.getId());
                UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(userId);
                if (userInfo != null) {
                    userInfo.setName(model.getName());
                    userInfo.setPortraitUri(AppUtil.getUserPhotoUri(model.getPhoto()));
                } else {
                    userInfo = AppUtil.getUserInfo(model);
                }
                Log.i(TAG, "the user info is:{}" + JsonUtil.toJson(userInfo));
                if (userId.equals(UserIdentityContext.getUserIdString())) {
                    LocalUserService.getInstance().updateUser(userInfo);
                }
                RongUserInfoManager.getInstance().refreshUserInfoCache(userInfo);
            }
        }
    }

    private void refreshGroupUserInfo(RongUserInfoManager manager, String groupId, List<GroupMemberModel> list) {
        if (StringUtil.isEmpty(list)) {
            return;
        }
        for (GroupMemberModel model : list) {
            manager.refreshGroupUserInfoCache(new GroupUserInfo(groupId, AppUtil.getTargetUserId(model.getUserId()), model.getNickName()));
        }
    }

    private void refreshGroupInfo(String data) {
        if (StringUtil.isEmpty(data)) {
            return;
        }

        GroupUpdateModel model = JsonUtil.parseObject(data, GroupUpdateModel.class);
        if (model == null) {
            return;
        }

        String groupId = AppUtil.getGroupId(model.getGroupId());
        RongUserInfoManager manager = RongUserInfoManager.getInstance();
        manager.refreshGroupInfoCache(new Group(groupId, model.getName(), AppUtil.getGroupPhotoUri(model.getPhoto())));
    }
}
